package com.southwind.controller;

import com.southwind.entity.Dormitory;
import com.southwind.entity.Student;
import com.southwind.service.BuildingService;
import com.southwind.service.DormitoryService;
import com.southwind.service.StudentServie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/dormitory")
public class DormitoryController {
    @Autowired
    private DormitoryService dormitoryService;
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private StudentServie studentServie;

    @GetMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("dormitorymanager");
        modelAndView.addObject("list",this.dormitoryService.list());
        modelAndView.addObject("buildingList",this.buildingService.list());
        return modelAndView;
    }

    @PostMapping("/search")
    public ModelAndView search(String key, String value){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("dormitorymanager");
        modelAndView.addObject("list",this.dormitoryService.search(key,value));
        modelAndView.addObject("buildingList",this.buildingService.list());
        return modelAndView;
    }

    @PostMapping("/save")
    public String save(Dormitory dormitory){
        this.dormitoryService.save(dormitory);
        return "redirect:/dormitory/list";
    }

    @PostMapping("/update")
    public String update(Dormitory dormitory){
        this.dormitoryService.update(dormitory);
        return "redirect:/dormitory/list";
    }

    @PostMapping("/delete")
    public String update(Integer id){
        this.dormitoryService.delete(id);
        return "redirect:/dormitory/list";
    }

    @PostMapping("/findByBuildingId")
    @ResponseBody   //返回数据给前端，如果是返回视图，就不用加
    public List findByBuildingId(Integer buildingId){
        List<Dormitory> byBuildingId = this.dormitoryService.findByBuildingId(buildingId);
        List list = new ArrayList();
        if(byBuildingId.size()>0)       //判断是否有宿舍
        {
            List<Student> studentList = this.studentServie.findByDormitoryId(byBuildingId.get(0).getId());
            list.add(byBuildingId);
            list.add(studentList);
        }else {
            list.add(new ArrayList<>());
            list.add(new ArrayList<>());
        }
        return list;
    }

}
